package com.alibaba.aliper.log;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.aliper.core.chart.AliperChart;
import com.alibaba.aliper.util.Dater;

public class ReporterLogImager {

	public static  void imager(File folder) {
		if(folder != null)
			imageSubFiles(folder);
	}

	private static void imageSubFiles(File folder) {
		if(folder.isDirectory()){
			File[] files = folder.listFiles();
			for (File file : files) {
				imageSubFiles(file);
			}
		} else if(folder.isFile()){
			image(folder);
		}
	}
	private static Color[] colors = new Color[]{Color.green,Color.RED,Color.GRAY,Color.blue};
	private static void image(File file) {
		BufferedReader reader = null;
		FileOutputStream output = null;
		try {
			if (file.getName().endsWith(".log")) {
				AliperChart chart = new AliperChart(file.getName(), "alibaba-platform-test", Color.WHITE,true);
				reader = new BufferedReader(
						new InputStreamReader(new FileInputStream(file)));
				String line = null;
				
				/* for sumary */
				long maxValueTime = 0;
				Double maxValue = null;
				long minValueTime = 0;
				Double minValue = null;
				long size = 0;
				double sum = 0;
				double avgValue = 0;
				/* for sumary */
				
				while((line = reader.readLine()) != null){
					Matcher matcher = pattern.matcher(line);
					if(matcher.find()){
						String lineName = matcher.group(1);
						long time = Long.parseLong(matcher.group(2));
						double value = Double.parseDouble(matcher.group(3));
						int index = chart.getLineCount();
						chart.getLine(lineName, colors[index], false).fill(time, value);
						
						size++;
						sum += value;
						// update max
						if(maxValue == null || value > maxValue){
							maxValue = value;
							maxValueTime = time;
						}
						// update min
						if(minValue == null || value < minValue){
							minValue = value;
							minValueTime = time;
						}
					}
				}
				
				avgValue = sum/size;
				
				byte[] data = chart.getImageData(1024, 600);
				output = new FileOutputStream(new File(file.getParent(),file.getName().replace(".log", ".jpg")));
				output.write(data);
				output.flush();
				output = new FileOutputStream(new File(file.getParent(),file.getName().replace(".log", "summary.html")));
				String html = getHTMLString(minValueTime,minValue,maxValueTime,maxValue,avgValue);
				output.write((html).getBytes());
				output.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(output != null){
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	private static String getHTMLString(long minValueTime, Double minValue,
			long maxValueTime, Double maxValue, double avgValue) {
		StringBuffer content = new StringBuffer();
		content.append("<html><head><title>sumary report</title></head><body>");
		content.append("<table border=\"1\">");
		content.append("<tr>");
		content.append("<th>Type</th>");
		content.append("<th>Value</th>");
		content.append("<th>Time</th>");
	    content.append("</tr>");
	    content.append("<tr>");
	    content.append("<td>Max</td>");
	    content.append("<td>"+maxValue+"</td>");
	    content.append("<td>"+Dater.getCNTime(maxValueTime)+"</td>");
	    content.append("</tr>");
	    content.append("<tr>");
	    content.append("<td>Min</td>");
	    content.append("<td>"+minValue+"</td>");
	    content.append("<td>"+Dater.getCNTime(minValueTime)+"</td>");
	    content.append("</tr>");
	    content.append("<tr>");
	    content.append("<td>Avg</td>");
	    content.append("<td>"+avgValue+"</td>");
	    content.append("<td>NA</td>");
	    content.append("</tr>");
	    content.append("</table>");
		content.append("</body></html>");
		return content.toString();
	}
	private static Pattern pattern = Pattern.compile(".*\\s+(\\w[^\\:]*)\\s*\\:\\s*\\(\\s*([^,]+)\\s*,\\s*([^\\)]+)\\).*");

	/**
	 * @param args
	 */
	public static void main(String[] args) {
			ReporterLogImager.imager("/home/cori-chenxx/Documents/myWork/aranda/aranda-1.1.0 hessian pool/线程池/服务down机等待队列取消，从崩溃中恢复");
	}

	public static void imager(String file) {
		imager(new File(file));
	}

}
